package com.mediacloud.app.newsmodule.fragment.baoliao.api;

import android.os.Handler;
import android.os.Looper;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;


public class ProgressRequestBody extends RequestBody {

    private File mFile;
    private MediaType contentType;
    private String mPath;
    private UploadCallbacks mListener;

    //每个RequestBody对应一个tag，存放在map中，保证计算的时候不会出现重复
    private String tag;

    //用于第二次实际写入的数据判断 显示progressListener
    private boolean mIsSecond;

    private static final int DEFAULT_BUFFER_SIZE = 2048;

    public interface UploadCallbacks {
        void onProgressUpdate(int percentage);

        void onError();

        void onFinish();
    }

    public ProgressRequestBody(final File file, MediaType contentType, String tag, final UploadCallbacks listener) {
        this.mFile = file;
        this.contentType = contentType;
        this.mListener = listener;
        this.tag = tag;
    }

    @Override
    public MediaType contentType() {
        // i want to upload only images
        return contentType;
    }

    @Override
    public long contentLength() throws IOException {
        return mFile.length();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {

        long fileLength = mFile.length();
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        FileInputStream in = new FileInputStream(mFile);
        long uploaded = 0;

        Handler handler = new Handler(Looper.getMainLooper());
        try {
            int read;
            if (mIsSecond)
                // update progress on UI thread
                handler.post(new ProgressUpdater(0, uploaded, fileLength));

            while ((read = in.read(buffer)) != -1) {

                if (mIsSecond)
                    // update progress on UI thread
                    handler.post(new ProgressUpdater(read, uploaded, fileLength));
                System.out.println("---------------" + "  " + "writeTo" + "uploaded=" + uploaded + "read=" + read);

                uploaded += read;
                sink.write(buffer, 0, read);
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    mListener.onFinish();
                }
            });
        } catch (Exception e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    mListener.onError();
                }
            });
        } finally {
            in.close();
        }

        mIsSecond = true;

    }

    private class ProgressUpdater implements Runnable {
        private long mUploaded;
        private long mTotal;
        private long read;

        public ProgressUpdater(long read, long uploaded, long total) {
            this.read = read;
            mUploaded = uploaded;
            mTotal = total;
        }

        @Override
        public void run() {
            mListener.onProgressUpdate((int) (100 * (mUploaded + read) / mTotal));
        }
    }
}